package com.farsunset.cim.component.handler;

import com.farsunset.cim.component.handler.annotation.CIMHandler;
import com.farsunset.cim.entity.CycleLocation;
import com.farsunset.cim.sdk.server.constant.ChannelAttr;
import com.farsunset.cim.sdk.server.handler.CIMRequestHandler;
import com.farsunset.cim.sdk.server.model.SentBody;
import com.farsunset.cim.service.CycleLocationService;
import io.netty.channel.Channel;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author xst
 * @description 客户端位置上报功能
 * @Date 2021/10/29
 */
@CIMHandler(key = "client_cycle_location") public class CycleLocationHandler implements CIMRequestHandler {
    @Resource private CycleLocationService locationService;

    private ExecutorService executorService = Executors.newFixedThreadPool(3);

    @Override public void process(Channel channel, SentBody body) {

        executorService.submit(new Runnable() {
            @Override public void run() {
                CycleLocation location = new CycleLocation();
                location.setUid(body.get("uid"));
                location.setNid(channel.attr(ChannelAttr.ID).get());
                location.setLatitude(getDouble(body.get("latitude")));
                location.setLongitude(getDouble(body.get("longitude")));
                location.setLocation(body.get("address"));
                locationService.add(location);
            }
        });
    }

    private Double getDouble(String val) {
        return StringUtils.hasLength(val) ? Double.parseDouble(val) : 0.0;
    }
}
